/*
evsync.js

Gears worker.

My purpose in life is to query the evurl for new events
and sync any found to the local store.

This requires json.js - make sure you pack them together before deploying.
*/

var wp = google.gears.workerPool;
var db = google.gears.factory.create('beta.database');
var timer = google.gears.factory.create('beta.timer');
db.open();

var pid = null;


wp.onmessage = function(url, sid) {
  pid = sid;
  wp.sendMessage('Looking for new events ...', sid);
  syncShareEvents(url, sid);
  };


wp.onerror = function(err) {
  wp.sendMessage('ERROR: ' + err, pid);
  };


var getResource = function(url, callback) {
  var req = google.gears.factory.create('beta.httprequest');
  req.open('GET', url);
  req.onreadystatechange = function() {
    if (req.readyState == 4) {
      callback(req.responseText);
      }
    };
  req.send();
  };


/*
Get latest event stored to NounEvents table.
*/
var getLatestStoredEvent = function() {
  var rs = db.execute('select * from NounEvents order by created desc limit 1');
  if (rs.isValidRow()) {
    var path = rs.fieldByName('path');
    var created = rs.fieldByName('created');
    return rs;
    }
  else {
    return null;
    }
  };


var syncShareEvents = function(url, sid) {
  // If no events exist, leave unspecified
  var qstr = '';
  // Get last stored pwun and use that as 'from' time
  var latest = getLatestStoredEvent();
  if (latest) {
    var qstr = '&since=' + latest.fieldByName('pwun');
    }

  getResource(url + qstr, function(response) {
    // TODO: Check response to see if it was a failure.
    var data = JSON.parse(response);
    var events = data.events;
    for (var i = 0; i < events.length; i++) {
      var entry = events[i];
      db.execute('insert into NounEvents values (?, ?, ?, ?, ?, ?, ?)', entry);
      }

    if (i) {
      wp.sendMessage('Synced ' + i + ' new evs to local store.', sid);
      }

    if (data.number_remaining > 0) {
      wp.sendMessage(
          'There are ' + data.number_remaining + ' new evs left to sync ...', sid);
      timer.setTimeout(function() {syncShareEvents(url, sid)}, 2000);
      }
    else {
      wp.sendMessage('Local store in sync.', sid);
      }
    });
  };
